import Vue from "vue";

const db = uniCloud.database();
const articleFilter = uniCloud.importObject("article-filter", {
  customUI: true,
});

const data = {
  redirectUrl: "", // 存储跳转的url
  articles: [], // 存储首页的默认tab对应的优惠券/文章列表
  isLoadingWhenAppInit: true,
  requestCount: 0,
  appConfig: null, // 存储应用配置
  categories: [], // 存储分类数据
  listTotalCount: 0, // 当前种类中，已经发表的文章数量
  bannerImages: [], // 存储banner图片url
};

export const mutations = {
  resetRedirectUrl() {
    store.redirectUrl = "";
  },

  // 开始请求时调用
  startRequest() {
    store.requestCount++;
    store.isLoadingWhenAppInit = true;
  },

  // 请求结束时调用
  endRequest() {
    store.requestCount--;
    if (store.requestCount <= 0) {
      store.requestCount = 0;
      store.isLoadingWhenAppInit = false;
    }
  },

  // 获取分类数据
  async fetchCategories() {
    try {
      const categoryRes = await db.collection("opendb-news-categories").get();
      const listTabs = categoryRes?.result?.data
        .map((item) => ({
          label: item.name, // 类别名称
          sort: item.sort, // 类别显示顺序
          category_id: item._id, // 类别 ID
        }))
        .sort((a, b) => a.sort - b.sort); // 根据 sort 排序

      store.categories = [...listTabs];

      return store.categories;
    } catch (e) {
      console.error("获取分类数据失败:", e);
    }
  },

  // 加载更多文章数据
  async loadMore(category_id) {
    try {
      const res = await articleFilter.loadMore(
        category_id,
        store.articles.length
      );
      const moreArticles = res?.data?.data;

      // 将新加载的文章追加到现有文章列表中
      store.articles = [...store.articles, ...moreArticles];
    } catch (e) {
      console.error("加载更多文章失败:", e);
      return [];
    }
  },

  // 按照类别加载数据
  async loadArticles(category_id) {
    try {
      const res = await articleFilter.getArticles(category_id);
      const articles = res?.data?.data;

      store.articles = [...articles];

      store.listTotalCount = res?.data?.affectedDocs || 0;
    } catch (e) {
      console.error(e);
    }
  },

  // 初始化应用数据
  async initAppData() {
    try {
      mutations.startRequest();
      await this.fetchCategories();
      const id = store.categories[0].category_id;
      await this.loadArticles(id);
      await this.fetchBanners();
    } catch (e) {
      console.error("初始化数据失败:", e);
    } finally {
      mutations.endRequest();
    }
  },

  // 获取banner数据
  async fetchBanners() {
    try {
      const bannerObj = uniCloud.importObject("banner", { customUI: true });
      const res = await bannerObj.getBanners();

      if (res.code === 200) {
        store.bannerImages = res.data.map((item) => item.bannerfile.url);
      }
    } catch (error) {
      console.error("获取banner失败:", error);
    }
  },
};

export const store = Vue.observable(data);
